package com.cb.controller.member.user;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;

import com.cb.common.util.EncryptUtil;
import com.cb.core.controller.BaseFormController;
import com.cb.domain.model.user.UserAccount;
import com.cb.domain.service.user.UserManager;

public class RegisterController extends BaseFormController{
	

	
	@Autowired
	private UserManager userManager=null;

	public RegisterController() {
		 setCommandName("user");
	     setCommandClass(UserAccount.class);
	}
	
	@Override
	protected ModelAndView onSubmit(HttpServletRequest request,
			HttpServletResponse response, Object command, BindException errors)
			throws Exception {
		
		UserAccount user=(UserAccount)command;
		String msg=null;
		String password= user.getPassword();
		password=EncryptUtil.md5Translate(password);
		user.setPassword(password);
		//validate the logic business data here [TODO]
		if(user.getUserId()==null){
			msg=getText("user.added",user.getUsername());
			user.setCreateTime(new Date());
		}else{
			msg=getText("user.updated",user.getUsername());
		}
		user.setStatus(Short.valueOf("1"));
		user.setUserType((short)1);
		userManager.save(user);
		
		saveMessage(request,msg);
		
		return new ModelAndView("/member/user/registerSucces").addObject("user", user);
	}
	
	@Override
	protected Object formBackingObject(HttpServletRequest request)
			throws Exception {
		UserAccount user=null;
		String userId=request.getParameter("userId");
		if(StringUtils.isNotEmpty(userId)){
			user=userManager.get(new Long(userId));
		}else{
			user=new UserAccount();
		}
		return user;
	}
	
}





	

